package cn.szzsi._web;

import cn.szzsi.common.kit.IdGen;
import cn.szzsi.common.kit.SessionUtil;
import cn.szzsi.common.kit.WeixinUtil;
import cn.szzsi.common.model.BrandStore;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.SiteConfig;
import cn.szzsi.service.WeiXinBusinessService;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.msg.in.*;
import com.jfinal.weixin.sdk.msg.in.event.*;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by yuanzheng on 2016/9/12.
 */
public class WeiXinBusinessController extends MsgControllerAdapter {
    private static final Log logger = Log.getLog(WeiXinBusinessController.class);

    private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool();

    private static final AtomicInteger lonum = new AtomicInteger(0);

    @Override
    public ApiConfig getApiConfig() {
        return SessionUtil.getApiConfigForB(WeiXinBusinessController.this);
    }


    /**
     * 实现父类抽方法，处理关注/取消关注消息
     */
    @Override
    protected void processInFollowEvent(final InFollowEvent inFollowEvent) {
        try {
            ApiConfigKit.setThreadLocalApiConfig(SessionUtil.getApiConfigForB(WeiXinBusinessController.this));
            if (InFollowEvent.EVENT_INFOLLOW_SUBSCRIBE.equals(inFollowEvent.getEvent())) {
                logger.debug("关注：" + inFollowEvent.getFromUserName());
                WeixinUtil.sendMsg(inFollowEvent.getFromUserName(), "亲，欢迎关注我们的公众平台!");
            } else if (InFollowEvent.EVENT_INFOLLOW_UNSUBSCRIBE.equals(inFollowEvent.getEvent())) {
                logger.debug("取消关注：" + inFollowEvent.getFromUserName());
            }
        } finally {
            ApiConfigKit.removeThreadLocalApiConfig();
        }

        renderText("success");
    }

    /**
     * 扫码关注
     * @param inQrCodeEvent
     */
    @Override
    protected void processInQrCodeEvent(final InQrCodeEvent inQrCodeEvent) {
        //ApiConfigKit.setThreadLocalApiConfig(SessionUtil.getApiConfigForB(WeiXinBusinessController.this));
        String sceneid = inQrCodeEvent.getEventKey();

        //如果商城二维码，则向商城post数据
        if (StringUtils.isNotBlank(sceneid)){
            if(sceneid.contains("qrscene_")){
                sceneid=sceneid.replace("qrscene_", "");
            }
            String apiid;//应用id
            String pids;///通过扫码推荐的用户所有上级id
            String openid=inQrCodeEvent.getFromUserName();
            Member pidMember= Member.dao.findById(sceneid);
            String shopId=pidMember.getStr("shopId");//推荐人和被推荐人的shopId相同
            if(!"0".equals(pidMember.getStr("pids"))){
                pids = pidMember.getStr("pids") + "," + pidMember.getStr("id");//本级的pids即为上级的pids+上级的pid
            }else{
                pids = sceneid;
            }

            Member member= Member.dao.isExistByOpenid(openid);
            if(member==null){//用户不存在
                SiteConfig siteConfig= SiteConfig.getByShopId(shopId);
                apiid=siteConfig.getStr("apiid");
                String registerIp=getRequest().getRemoteAddr();
                String code = IdGen.get().nextId(10);
                Member m = WeiXinBusinessService.processCommendUserInfo(sceneid,pids,shopId,apiid,openid,registerIp,code);
                /*if(StrKit.notBlank(pids)){
                    for(String s:pids.split(",")){
                        UserService.us.sendFocusMSG(apiid,s,m);
                    }
                }*/
            }

        }
        //ApiConfigKit.removeThreadLocalApiConfig();
        OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
        outMsg.setContent("亲，欢迎关注我们的公众平台!");
        render(outMsg);
    }


    @Override
    protected void processInTextMsg(InTextMsg inTextMsg) {
        OutTextMsg outMsg = new OutTextMsg(inTextMsg);
        outMsg.setContent("亲，欢迎关注我们的公众平台!");
        render(outMsg);
    }

    @Override
    protected void processInMenuEvent(InMenuEvent inMenuEvent) {
        renderNull();
    }

    /**
     * 实现父类抽方法，处理门店推送事件
     * @param inPoiCheckNotifyEvent
     */
    @Override
    protected void processInPoiCheckNotifyEvent(InPoiCheckNotifyEvent inPoiCheckNotifyEvent) {
        String xmlMsg = getInMsgXml();
        if(StrKit.notBlank(xmlMsg)){
            System.out.println("xmlMsg---------------"+xmlMsg);
            Map<String,String>params= PaymentKit.xmlToMap(xmlMsg);
            String type=params.get("MsgType");
            if("event".equals(type)&& StrKit.notBlank(params.get("PoiId"))){//微信门店审核事件推送
                System.out.println("------------------微信门店审核事件推送");
                BrandStore bs= BrandStore.dao.getByPoiId(params.get("PoiId"));
                bs.set("createTime",params.get("CreateTime"));
                if("succ".equals(params.get("Result"))){
                    bs.set("status",2);
                }else{
                    bs.set("status",3);
                }
                bs.set("msg",params.get("msg"));
                bs.update();
            }
        }

    }

    /**
     * 实现父类抽象方法,处理卡券领取事件
     */
    @Override
    protected void processInUserViewCardEvent(InUserViewCardEvent msg) {
        System.out.println("11111111111111111111111");
    }

    protected void processInSubmitMemberCardEvent(InSubmitMemberCardEvent msg) {
        System.out.println("2222222");
    }

    protected void processInUpdateMemberCardEvent(InUpdateMemberCardEvent msg) {
        System.out.println("33333333");
    }

    protected void processInUserPayFromCardEvent(InUserPayFromCardEvent msg) {
        System.out.println("444444444444444444");
    }

    protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
        System.out.println("555555555555555555555");
    }

    protected void processInTemplateMsgEvent(InTemplateMsgEvent inTemplateMsgEvent) {
        System.out.println("666666666666666666666");
    }

    protected void processInMassEvent(InMassEvent inMassEvent) {
        System.out.println("7777777777777777777777");
    }

    protected void processInShortVideoMsg(InShortVideoMsg inShortVideoMsg) {
        System.out.println("8888888888888888888888");
    }

    protected void processInCustomEvent(InCustomEvent inCustomEvent) {
        System.out.println("999999999999999999999");
    }

    protected void processInShakearoundUserShakeEvent(InShakearoundUserShakeEvent inShakearoundUserShakeEvent) {
        System.out.println("101010101041040");
    }

    protected void processInVerifySuccessEvent(InVerifySuccessEvent inVerifySuccessEvent) {
        System.out.println("1111111111111111111111111111111111");
    }

    protected void processInVerifyFailEvent(InVerifyFailEvent inVerifyFailEvent) {
        System.out.println("12121212121212");
    }



    protected void processInWifiEvent(InWifiEvent inWifiEvent) {
        System.out.println("13131313123");
    }


    protected void processInMerChantOrderEvent(InMerChantOrderEvent inMerChantOrderEvent) {
        System.out.println("141414141414");
    }

    protected void processIsNotDefinedEvent(InNotDefinedEvent inNotDefinedEvent) {
        System.out.println("1511515151515151515");
        System.out.println(getInMsgXml());
    }

    protected void processIsNotDefinedMsg(InNotDefinedMsg inNotDefinedMsg) {
        System.out.println("16161616161616161612");
    }


    protected void processInImageMsg(InImageMsg inImageMsg) {
        System.out.println("16161616161616161613");
    }

    protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
        System.out.println("16161616161616161614");
    }

    protected void processInVideoMsg(InVideoMsg inVideoMsg) {
        System.out.println("16161616161616161615");
    }

    protected void processInLocationMsg(InLocationMsg inLocationMsg) {
        System.out.println("16161616161616161616");
    }

    protected void processInLinkMsg(InLinkMsg inLinkMsg) {
        System.out.println("16161616161616161617");
    }


    protected void processInLocationEvent(InLocationEvent inLocationEvent) {
        renderNull();
    }

}
